package com.example.demo.server.dao;

import com.example.demo.server.model.LoginInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class LoginInfoDao {

    public int setSession(LoginInfo loginInfo) {
        Connection connection = null;
        PreparedStatement statement = null;
        int ret = 0;
        try {
            connection = DBUtils.getConnection();
            String sql = "insert into logininfo values(?, ?)";
            statement = connection.prepareStatement(sql);
            // 设置信息
            statement.setString(1, loginInfo.getSessionId());
            statement.setString(2, loginInfo.getSession());
            // 存储
            ret = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection, statement, null);
        }
        return ret;
    }


    public String getSession(String sessionId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet set = null;
        String session = null;
        try {
            connection = DBUtils.getConnection();
            String sql = "select * from logininfo where sessionid = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, sessionId);
            set = statement.executeQuery();
            if(set.next()) {
                session = set.getString("session");
            }else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection, statement, set);
        }
        return session;
    }

    public int removeSession(String sessionId) {
        Connection connection = null;
        PreparedStatement statement = null;
        int ret = 0;
        try {
            connection = DBUtils.getConnection();
            String sql = "delete from logininfo where sessionid = ?";
            statement = connection.prepareStatement(sql);
            // 设置信息
            statement.setString(1, sessionId);
            // 存储
            ret = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection, statement, null);
        }
        return ret;
    }

}
